const api = require("../../request/api")
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		phone: "",
		code: "",
		time: 0
	},


	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh() {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom() {

	},
	onLoad() {
		// 判断是否有登录的状态
		let userInfo = wx.getStorageSync('userInfo')
		let token = wx.getStorageSync('token')
		if (token) {
			wx.redirectTo({
				url: '/pages/index/index',
			})
		}
	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage() {

	},
	// 手机号登录
	async onLogin() {
		let {
			phone,
			code,

		} = this.data
		if (!this.validatePhoneNumber(phone)) {
			wx.showToast({
				title: '手机号格式错误',
				icon: "error"
			});
			return;
		}
		if (code != 5000) {
			wx.showToast({
				title: '验证码错误',
				icon: "error"
			});
			return;
		}
		// 请求登录接口
		let res = await api.phoneLogin(phone, code)
		console.log(res)
		if (res.token) {
			wx.setStorageSync('token', res.token)
			wx.setStorageSync('userInfo', res.data)
			// 跳转至首页
			wx.switchTab({
				url: '/pages/index/index',
			})
		} else {

			wx.showToast({
				title: '系统错误',
				icon: "error"
			})
		}
	},
	onGetCode() {
		let phone = this.data.phone;
		if (!this.validatePhoneNumber(phone)) {
			wx.showToast({
				title: '手机号格式错误',
				icon: "error"
			});
			return;
		}


		let time = 60;
		this.setData({
			time: time
		});
		let timer = setInterval(() => {
			time--; // 正确递减时间变量
			this.setData({
				time: time
			});

			if (time <= 0) {
				clearInterval(timer);

			}
		}, 1000);
	},


	validatePhoneNumber(phoneNumber) {
		const phoneRegex = /^1[3-9]\d{9}$/;
		return phoneRegex.test(phoneNumber);
	},
	onCodeInput(e) {
		let input = e.detail.value
		this.setData({
			code: input
		})
	},
	onPhoneNumberInput(e) {
		let input = e.detail.value
		this.setData({
			phone: input
		})
	}
})